package com.example.yijian.edit.view.popup;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yijian.R;
import com.example.yijian.edit.animation.AnimationAdapter;
import com.example.yijian.edit.background.SpaceItemDecoration;
import com.example.yijian.edit.data.AssetItem;
import com.example.yijian.edit.data.FilterItem;
import com.example.yijian.edit.data.ParseJsonFile;
import com.example.yijian.edit.view.HorizontalSeekBar;
import com.example.yijian.utils.Util;
import com.example.yijian.utils.Utils;
import com.example.yijian.utils.asset.NvAsset;
import com.example.yijian.utils.asset.NvAssetManager;
import com.example.yijian.utils.datainfo.StickerInfo;
import com.example.yijian.utils.datainfo.TimelineData;
import com.google.android.material.tabs.TabLayout;
import com.meicam.sdk.NvsTimelineAnimatedSticker;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static com.example.yijian.utils.StringUtils.getString;

public class VideoAnimationPopup extends BaseCommonPopupWindow {

    private final String TAG = "VideoAnimationPopup";
    private final String PATH_OUT_ANIMATION = "stickeranimation/out";
    private final String PATH_IN_ANIMATION = "stickeranimation/in";
    private final String PATH_PERIOD_ANIMATION = "stickeranimation/period";

    private int IN_OUT_ANIMATION_DEFAULT_DURATION = 500;
    private static final float DEFAULT_DURATION_IN = 0.5f;

    private int CATEGORY_IN_ANIMATION = 7;
    private int CATEGORY_OUT_ANIMATION = 8;
    private int CATEGORY_ANIMATION = 9;

    private TabLayout mTabAnimation;
    private RecyclerView mRvAnimationList;
    private HorizontalSeekBar stickerSeekbar;
    private ImageView ivFinish;

    private int mSelectedAniPos;
    private int mSelectedInAniPos;
    private int mSelectedOutAniPos;

    private int mCurStickerZVal;
    private List<StickerInfo> mStickerInfoListClone;
    private NvsTimelineAnimatedSticker curAnimatedSticker;//当前选中的贴纸
    private NvAssetManager mAssetManager;
    private int[] ANIMATION = new int[]{R.string.march_in_animation, R.string.march_out_animation, R.string.combination_animation};
    private AnimationAdapter mAnimationAdapter;
    private ArrayList<FilterItem> mAnimationDataList;
    private int mAssetType = NvAsset.ASSET_ANIMATION_IN;
    private int curRatio = NvAsset.AspectRatio_NoFitRatio;

    public VideoAnimationPopup(Context context) {
        super(context);
        setContentView(R.layout.popup_animation_popup);
        initView();
        for (int value : ANIMATION) {
            mTabAnimation.addTab(mTabAnimation.newTab().setText(value));
        }
        curRatio = TimelineData.instance().getMakeRatio();
    }

    public void initData(int pos) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mRvAnimationList.setLayoutManager(layoutManager);
        mAnimationAdapter = new AnimationAdapter(getContext());
        mRvAnimationList.setAdapter(mAnimationAdapter);
        mRvAnimationList.addItemDecoration(new SpaceItemDecoration(0, 15));
        displayTabAnimation(pos);
        checkSelectedTab();
        initListener();
    }

    private void initListener() {
        ivFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        mTabAnimation.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                displayTabAnimation(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//        stickerSeekbar.setOnRangeListener(new HorizontalSeekBar.onRangeListener() {
//            @Override
//            public void onRange(float left, float right) {
//                if (curAnimatedSticker == null) {
//                    return;
//                }
//                int index = getStickerIndex(mCurStickerZVal);
//                StickerInfo stickerInfo = mStickerInfoListClone.get(index);
//                int leftValue = (int) (Float.parseFloat(String.format(getString(R.string.format_1f), left)) * 1000);
//                int rightValue = (int) (Float.parseFloat(String.format(getString(R.string.format_1f), right)) * 1000);
//                Log.d(TAG, "seekBar onRange left:" + left + " right:" + right + " leftValue:" + leftValue + " rightValue:" + rightValue);
//                //组合动画与出入动画互斥(出入动画不互斥)。前者默认时长0.5s后者0.6s
//                if (!TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerPeriodAnimationPackageId())) {
//                    if (leftValue <= 100) {
//                        //组合动画最小值可设置成100ms
//                        leftValue = 100;
//                        stickerSeekbar.setLeftProgress(leftValue);
//                    }
//                    curAnimatedSticker.setAnimatedStickerAnimationPeriod(leftValue);
//                    if (stickerInfo != null) {
//                        stickerInfo.setPeriodAnimationDuration(leftValue);
//                    }
//                } else {
//                    if (!TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerInAnimationPackageId())) {
//                        if (stickerSeekbar.getMaxProgress() - leftValue < IN_OUT_ANIMATION_DEFAULT_DURATION && TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerOutAnimationPackageId())) {
//                            //如果设置入动画后，剩余的时间小于默认时间500毫秒（出入动画默认时长500ms，不论设置不设置出动画），且此时没有出动画，则把出动画时长设置成0
//                            curAnimatedSticker.setAnimatedStickerOutAnimationDuration(0);
//                        }
//                        if (stickerInfo != null) {
//                            stickerInfo.setInAnimationDuration(leftValue);
//                        }
//                        curAnimatedSticker.setAnimatedStickerInAnimationDuration(leftValue);
//                    }
//                    if (!TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerOutAnimationPackageId())) {
//                        //如果设置出动画后，剩余的时间小于默认时间500毫秒（出入动画默认时长500ms，不论设置不设置入动画），且此时没有入动画，则把入动画时长设置成0
//                        if (stickerSeekbar.getMaxProgress() - rightValue < IN_OUT_ANIMATION_DEFAULT_DURATION && TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerInAnimationPackageId())) {
//                            curAnimatedSticker.setAnimatedStickerInAnimationDuration(0);
//                        }
//                        if (stickerInfo != null) {
//                            stickerInfo.setOutAnimationDuration(rightValue);
//                        }
//                        curAnimatedSticker.setAnimatedStickerOutAnimationDuration(rightValue);
//                    }
//                }
////                if (mVideoFragment != null) {
////                    mVideoFragment.stopEngine();
////                }
//            }
//
//            @Override
//            public void onTouchUpLeft(boolean leftFlag) {
//                Log.d(TAG, "seekBar onTouchUpLeft leftFlag:" + leftFlag);
//                if (curAnimatedSticker == null) return;
//                long playTimeStart = curAnimatedSticker.getInPoint();
//                if (leftFlag) {
//                    //组合动画或者入动画 combAnimation or inAnimation
//                    playTimeStart = curAnimatedSticker.getInPoint();
//                } else {
//                    //出动画 outAnimation
//                    if (!TextUtils.isEmpty(curAnimatedSticker.getAnimatedStickerOutAnimationPackageId())) {
//                        playTimeStart = curAnimatedSticker.getOutPoint() - curAnimatedSticker.getAnimatedStickerOutAnimationDuration() * 1000;
//                    }
//                }
////                playVideo(playTimeStart, curAnimatedSticker.getOutPoint());
//            }
//        });
        mAnimationAdapter.setOnItemClickListener(new AnimationAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int pos) {
                mAnimationAdapter.setSelectItem(pos);
                int type;
                int typePos = mTabAnimation.getSelectedTabPosition();
                if (typePos == 0) {
                    type = NvAsset.ASSET_ANIMATION_IN;
                    mSelectedInAniPos = pos;
                    mSelectedAniPos = 0;
                } else if (typePos == 1) {
                    type = NvAsset.ASSET_ANIMATION_OUT;
                    mSelectedOutAniPos = pos;
                    mSelectedAniPos = 0;
                } else {
                    type = NvAsset.ASSET_ANIMATION_COMPANY;
                    mSelectedAniPos = pos;
                    mSelectedOutAniPos = 0;
                    mSelectedInAniPos = 0;
                }
//                applyStickerAnimation(type, selectedItem);
                displayAnimationProgress(pos > 0 && mAnimationAdapter.getSelectFilterItem() != null, type, mAnimationAdapter.getSelectFilterItem());
//                mStickerAnimationListener.onItemClick(pos, type, mAnimationAdapter.getSelectedItem());
            }
        });

    }

    public void initAnimationDataList() {
        FilterItem selectFilterItem = null;
        if (mAnimationAdapter != null) {
            selectFilterItem = mAnimationAdapter.getSelectFilterItem();
        }
        mAnimationDataList = new ArrayList<>();

        FilterItem filterItem = new FilterItem();
        filterItem.setFilterMode(FilterItem.FILTERMODE_BUILTIN);

        filterItem.setFilterName("无");
        filterItem.setImageId(R.mipmap.none);
        mAnimationDataList.add(filterItem);

        ArrayList<NvAsset> animationList = getLocalData();
        String bundlePath = "animation/in/info_Zh.txt";
        if (mAssetType == NvAsset.ASSET_ANIMATION_OUT) {
            bundlePath = "animation/out/info_Zh.txt";
        } else if (mAssetType == NvAsset.ASSET_ANIMATION_COMPANY) {
            bundlePath = "animation/company/info_Zh.txt";
        }
        Util.getBundleFilterInfo(getContext(), animationList, bundlePath);
        int ratio = TimelineData.instance().getMakeRatio();
        for (NvAsset asset : animationList) {
            if ((ratio & asset.aspectRatio) == 0)
                continue;

            FilterItem newFilterItem = new FilterItem();
            if (asset.isReserved()) {
                /*
                 * 加载assets/animation文件夹下的图片
                 * Load images in the assets / animation folder
                 * */
                String coverPath = "asset://android_asset/animation/in/";
                if (mAssetType == NvAsset.ASSET_ANIMATION_OUT) {
                    coverPath = "asset://android_asset/animation/out/";
                } else if (mAssetType == NvAsset.ASSET_ANIMATION_COMPANY) {
                    coverPath = "asset://android_asset/animation/company/";
                }
                coverPath += asset.uuid;
                coverPath += ".webp";
                asset.coverUrl = coverPath;
            }
            newFilterItem.setFilterMode(FilterItem.FILTERMODE_PACKAGE);
            newFilterItem.setFilterName(asset.name);
            newFilterItem.setPackageId(asset.uuid);
            newFilterItem.setImageUrl(asset.coverUrl);
            newFilterItem.setPostPackage(asset.isPostPackage == 1);
            mAnimationDataList.add(newFilterItem);
        }
        if (null != mAnimationAdapter) {
            mAnimationAdapter.setAnimationDataList(mAnimationDataList);
            mAnimationAdapter.setSelectItem(selectFilterItem);
            mAnimationAdapter.notifyDataSetChanged();
        }
    }


    private ArrayList<NvAsset> getLocalData() {
        mAssetManager = NvAssetManager.sharedInstance();
        mAssetManager.searchLocalAssets(mAssetType);
        String bundlePath = "animation/in";
        if (mAssetType == NvAsset.ASSET_ANIMATION_OUT) {
            bundlePath = "animation/out";
        } else if (mAssetType == NvAsset.ASSET_ANIMATION_COMPANY) {
            bundlePath = "animation/company";
        }
        mAssetManager.searchReservedAssets(mAssetType, bundlePath);
        return mAssetManager.getUsableAssets(mAssetType, NvAsset.AspectRatio_All, 0);
    }

    /***
     * 展示动画Tab对应的内容
     */
    private void displayTabAnimation(int pos) {
        if (mAnimationAdapter == null) {
            return;
        }
        int type;
        int selectPos = 0;
        if (pos == 0) {
            mAssetType = NvAsset.ASSET_ANIMATION_IN;
            selectPos = mSelectedInAniPos;
            initAnimationDataList();
        } else if (pos == 1) {
            mAssetType = NvAsset.ASSET_ANIMATION_OUT;
            selectPos = mSelectedOutAniPos;
            initAnimationDataList();
        } else {
            mAssetType = NvAsset.ASSET_ANIMATION_COMPANY;
            selectPos = mSelectedAniPos;
            initAnimationDataList();
        }
        mAnimationAdapter.setSelectPos(selectPos);
        mAnimationAdapter.notifyDataSetChanged();
//        if (mStickerAnimationListener != null) {
//            mStickerAnimationListener.onItemClick(selectPos, type, mAnimationAdapter.getSelectedItem());
//        }
    }

    /**
     * 展示动画的进度--
     * 注意:出入动画和组合动画互斥
     * Show the progress of the animation-
     * note: the in and out animation and the combined animation are mutually exclusive
     */
    private void displayAnimationProgress(boolean visible, int type, FilterItem filterItem) {
        displaySeekBar(visible);
        if (!visible || filterItem == null) return;
        String mAnimationId = filterItem.getPackageId();
        if (type == NvAsset.ASSET_ANIMATION_IN) {
            if (TextUtils.isEmpty(mAnimationId)) {
                stickerSeekbar.setLeftMoveIcon(0);
            } else {
                //1.判断是否有出动画 无则重置
                if (TextUtils.isEmpty(mAnimationId)) {
                    stickerSeekbar.reset();
                    stickerSeekbar.setRightMoveIcon(0);
                    stickerSeekbar.setMoveIconSize(20, 35);
                }
                long duration = getAnimationDurationValue(mAnimationId, type);
                //Log.d("lhz", "duration=" + duration + "**type=" + type);
                stickerSeekbar.setMoveIconLowPadding(10);
                stickerSeekbar.setLeftMoveIcon(R.mipmap.bar_left);
                stickerSeekbar.setLeftProgress((int) duration);
            }
        } else if (type == NvAsset.ASSET_ANIMATION_OUT) {
            if (TextUtils.isEmpty(mAnimationId)) {
                stickerSeekbar.setRightMoveIcon(0);
            } else {
                //1.判断是否有入动画 无则重置
                //Determine whether there is an incoming animation, reset if not
                if (TextUtils.isEmpty(mAnimationId)) {
                    stickerSeekbar.reset();
                    stickerSeekbar.setMoveIconSize(20, 35);
                    stickerSeekbar.setLeftMoveIcon(0);
                }
                int duration = (int) getAnimationDurationValue(mAnimationId, type);
                stickerSeekbar.setMoveIconLowPadding(10);
                stickerSeekbar.setRightMoveIcon(R.mipmap.bar_right);
                stickerSeekbar.setRightProgress(duration);
                //  Log.d("lhz", "duration=" + duration + "**type=" + type);
            }
        } else {
            if (TextUtils.isEmpty(mAnimationId)) {
                stickerSeekbar.reset();
                stickerSeekbar.setVisibility(View.GONE);
                return;
            }
            int duration = (int) getAnimationDurationValue(mAnimationId, type);
            stickerSeekbar.reset();
            stickerSeekbar.setMoveIconSize(20, 20);
            stickerSeekbar.setLeftMoveIcon(R.mipmap.round_white);
            stickerSeekbar.setLeftProgress(duration);
            //Log.d("lhz", "duration=" + duration + "**type=" + type);
        }
    }

    /**
     * 获取动画对应的时长情况
     * 1.先拿到默认的动画时长 不同动画类型市场不懂
     * 2.如果该动画类型之前设置过时长，则拿到这个时长作为动画的时长
     * <p>
     * Get the duration of the animation
     * 1. Get the default animation duration first. Different animation types don’t understand the market
     * 2. If the duration of the animation type is set before, then this duration will be used as the duration of the animation
     *
     * @param mAnimationId
     * @param animationType
     * @return
     */
    private long getAnimationDurationValue(String mAnimationId, int animationType) {
        //获取到特效对应的值,如果手动设置过 ，会在回调中保存，没设置过，则使用默认值
        //默认值 组合动画为最大时长，其他未0.5s
        long value = 0;
        if (animationType == NvAsset.ASSET_ANIMATION_COMPANY) {
//            value = getClipDuration(mSelectedClipPosition);
        } else {
            value = (long) (DEFAULT_DURATION_IN * 1000 * 1000);
        }/*else{
            value = (long) (DEFAULT_DURATION_IN*1000*1000);
        }*/

//        //mAnimationId 非空代表选择有效动画效果, 拿到这个packageId之前选择的动画时长设置
//        if (!TextUtils.isEmpty(mAnimationId)) {
//            //如果该片段设置过动画，此时去获取动画的时长
//            if (mClipVideoFxAnimationDurationMap.containsKey(mSelectedClipPosition)) {
//                //拿到该片段设置过的当前类型的动画的时长作为返回值
//                ConcurrentHashMap<String, Long> map = mClipVideoFxAnimationDurationMap.get(mSelectedClipPosition);
//
//                //遍历这个片段设置过的动画列表 ， 如果 当前类型的动画列表中包含这个，直接返回这个动画对应的时长,否则不处理value
//                if (null != map && map.size() > 0) {
//
//                    Set<String> keySet = map.keySet();
//                    for (String key : keySet) {
//                        if (!TextUtils.isEmpty(key) && containAnimationId(key)) {
//                            value = map.get(key);
//                            break;
//                        }
//                    }
//                }
//            }
//        }

//        return value;
        return (long) (DEFAULT_DURATION_IN * 1000 * 1000);
    }

    private int getStickerIndex(int zValue) {
        int index = -1;
        if (mStickerInfoListClone != null) {
            int count = mStickerInfoListClone.size();
            for (int i = 0; i < count; ++i) {
                int zVal = mStickerInfoListClone.get(i).getAnimateStickerZVal();
                if (zValue == zVal) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }

    /**
     * 控制是否展示seekbar
     * displaySeekBar
     *
     * @param visible
     */
    private void displaySeekBar(boolean visible) {
        if (visible) {
            if (stickerSeekbar.getVisibility() != View.VISIBLE) {
                stickerSeekbar.setVisibility(View.VISIBLE);
            }
        } else {
            if (stickerSeekbar.getVisibility() == View.VISIBLE) {
                stickerSeekbar.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 检测是动画的tab按照要求显示,仅仅第一次初始化会使用
     */
    public void checkSelectedTab() {
        int selectedTabPosition = mTabAnimation.getSelectedTabPosition();
        if (mSelectedAniPos > 0 && selectedTabPosition != 2) {
            //如果设置了组合动画，但是组合动画的tab没有被选中，则选中
            TabLayout.Tab animationTab = mTabAnimation.getTabAt(2);
            if (animationTab != null) {
                animationTab.select();
            }
        } else if (mSelectedOutAniPos > 0 && mSelectedInAniPos <= 0 && selectedTabPosition != 1) {
            //如果仅仅设置了出动画动画，但是出动画的tab没有被选中，则选中
            TabLayout.Tab animationTab = mTabAnimation.getTabAt(1);
            if (animationTab != null) {
                animationTab.select();
            }
        }
    }


    /**
     * 获取对应的position
     *
     * @param animationId
     * @param assetItems
     * @return
     */
    private int getSelectedPosInList(String animationId, List<AssetItem> assetItems) {
        if (TextUtils.isEmpty(animationId) || assetItems == null || assetItems.isEmpty()) return 0;
        for (int i = 0; i < assetItems.size(); i++) {
            if (TextUtils.equals(animationId, assetItems.get(i).getAsset().uuid)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 处理asset资源数据
     *
     * @param assetType int 资源类型
     * @param assetPath String 资源路径
     * @param assetList List<AssetItem> 资源列表
     */
    private void dealAssetData(int assetType, String assetPath, List<AssetItem> assetList) {
        mAssetManager.searchLocalAssets(assetType);
        mAssetManager.searchReservedAssets(assetType, assetPath);
        ArrayList<NvAsset> usableAsset = getAssetsDataList(assetType);
        String jsonBundlePath = assetPath + "/info.json";
        ArrayList<ParseJsonFile.FxJsonFileInfo.JsonFileInfo> infoLists = ParseJsonFile.readBundleFxJsonFile(getContext(), jsonBundlePath);
        if (infoLists != null) {
            for (ParseJsonFile.FxJsonFileInfo.JsonFileInfo jsonFileInfo : infoLists) {
                for (NvAsset asset : usableAsset) {
                    if (asset == null)
                        continue;
                    if (TextUtils.isEmpty(asset.uuid))
                        continue;
                    if (asset.isReserved && asset.uuid.equals(jsonFileInfo.getFxPackageId())) {
                        if (Utils.isZh()) {
                            asset.name = jsonFileInfo.getName_Zh();
                        } else {
                            asset.name = jsonFileInfo.getName();
                        }
                        if (!TextUtils.isEmpty(jsonFileInfo.getFitRatio())) {
                            try {
                                asset.aspectRatio = Integer.parseInt(jsonFileInfo.getFitRatio());
                            } catch (Exception e) {
                                Log.e(TAG, "Exception=" + e);
                                return;
                            }
                        }
                        StringBuilder coverPath = new StringBuilder();
                        coverPath.append("asset://android_asset/");
                        coverPath.append(assetPath);
                        coverPath.append("/");
                        coverPath.append(jsonFileInfo.getImageName());
                        asset.coverUrl = coverPath.toString();
                    }
                }
            }
        }
        if (assetList == null) {
            return;
        }
        AssetItem firstItem = new AssetItem();
        NvAsset firstAsset = new NvAsset();
        firstAsset.name = getString(R.string.timeline_fx_none);
        firstItem.setImageRes(R.mipmap.square_clear);
        firstItem.setAssetMode(AssetItem.ASSET_NONE);
        firstItem.setAsset(firstAsset);
        assetList.add(firstItem);
        for (NvAsset asset : usableAsset) {
            if (asset == null)
                continue;
            if (TextUtils.isEmpty(asset.uuid))
                continue;
            if ((curRatio & asset.aspectRatio) == 0) {
                /*
                 * 制作比例不适配，不加载
                 * Production proportions do not fit, do not load
                 * */
                continue;
            }
            AssetItem assetItem = new AssetItem();
            assetItem.setAsset(asset);
            assetItem.setAssetMode(AssetItem.ASSET_LOCAL);
            assetList.add(assetItem);
        }
    }

    /*
     * 获取下载到手机路径下的素材，包括assets路径下自带的素材
     * Get the material downloaded to the mobile phone path,
     * including the material that comes with the assets path
     * */
    private ArrayList<NvAsset> getAssetsDataList(int assetType) {
        return mAssetManager.getUsableAssets(assetType, NvAsset.AspectRatio_All, 0);
    }

    private void initView() {
        mTabAnimation = findViewById(R.id.tab_animation);
        mRvAnimationList = findViewById(R.id.rv_list_animation);
        stickerSeekbar = findViewById(R.id.sticker_style_seek_bar);
        stickerSeekbar.setTransformText(1000, 1);
        ivFinish = findViewById(R.id.iv_animation_finish);
    }

}
